package appbase.jwt;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JWTKit {

	public static long JWT_TOKEN_TTL_MILLS = 24 * 60 * 60 * 1000;
    public static String APP_BASE64_JWT_SECURITY_KEY = "PWrcVtr8923rTgksExTBDUEscfb1Wu4O";
	
	
	
	public static String createJWT(String id, String subject, long ttlMillis, String base64Security) 
	{

		// The JWT signature algorithm we will be using to sign the token
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);

		// We will sign our JWT with our ApiKey secret
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		// Let's set the JWT Claims
		JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject)
				.signWith(signatureAlgorithm, signingKey);

		// if it has been specified, let's add the expiration
		if (ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}

		// Builds the JWT and serializes it to a compact, URL-safe string
		return builder.compact();
	}

	/**
	 * 解析并验证jwt token，当验证不通过时，会抛出异常
	 * @param jwt
	 * 			jwt token
	 * @param base64Security 
	 * 			安全密钥 基于base64算法生成
	 * @return
	 */
	public static Claims parseJWT(String jwt, String base64Security) 
	{
		try {
			Claims claims = Jwts.parser()
					.setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
					.parseClaimsJws(jwt)
					.getBody();
			return claims;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
